from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required

from models import User

api = Blueprint('auth_api', __name__)

@api.route('/', methods=['POST'])
def login():
    username = request.form.get('username', '').strip()
    password = request.form.get('password', '').strip()

    user = User.query.filter_by(username=username).first()
    if user is None or not user.check_password(password):
        return jsonify({'error': '用户名或密码错误'}), 401

    token = create_access_token(identity=str(user.id))
    return jsonify({'message': '登录成功', 'token': token, 'user': user.to_dict()})

# 校验token 获取登录用户信息
@api.route('/user', methods=['POST'])
@jwt_required()
def get_current_user():
    auth_header = request.headers.get('Authorization', '')
    print('前端传来的 Authorization 头:', auth_header)

    uid = get_jwt_identity()
    print('JWT 识别出的 uid:', uid)

    user = User.query.filter_by(id=uid).first()
    if user:
        return jsonify({'code': 0, 'data': {'username': user.username}})
    return jsonify({'code': 1, 'msg': '用户不存在'})
